package com.yifeng.repo.endpoint.security.redis.worker;

import com.yifeng.repo.endpoint.security.redis.client.AbstractJedisCommand;
import com.yifeng.repo.endpoint.security.redis.client.JedisClient;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

/**
 * Created by daibing on 2022/8/9.
 */
public class RedisLockWorker {
    private static final String LOCK_SUCCESS = "OK";
    private final JedisClient jedisClient;

    public RedisLockWorker(JedisClient jedisClient) {
        this.jedisClient = jedisClient;
    }

    public boolean lock(String key, String value, long expireMillis) {
        SetParams params = SetParams.setParams().nx().px(expireMillis);
        String lockResult = new AbstractJedisCommand<String>() {
            @Override
            protected String doRun(Jedis jedis) {
                return jedis.set(key, value, params);
            }
        }.doExecute(jedisClient);
        return LOCK_SUCCESS.equals(lockResult);
    }

    public boolean unlock(String key, String value) {
        String lua = "if redis.call(\"get\", KEYS[1]) == ARGV[1] then return redis.call(\"del\", KEYS[1]) else return 0 end";
        Object unlockResult = new AbstractJedisCommand<Object>() {
            @Override
            protected Object doRun(Jedis jedis) {
                return jedis.eval(lua, 1, key, value);
            }
        }.doExecute(jedisClient);
        return Long.valueOf(1) == unlockResult;
    }

}
